package demo.fristserice.common.result;


import com.fasterxml.jackson.databind.ObjectMapper;
import demo.fristserice.common.exception.EmptyUtil;
import demo.fristserice.common.exception.MyException;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;

/**
 * @Auther: xurs
 * @Date: 19-3-11 13:34
 * @Description:
 */
public class  Data2Object  {

    /**
     * @author: xurs
     * @date: 19-3-11
     * @Description:  Object(LinkedHashMap)转原对象
     */
    public static<T> T linkedHashMap2Object(Result result,Class<T> clazz){
        if(result.getCode().equals(ResultEnum.ERROR.getCode())){
                throw new MyException(ResultEnum.ERROR.getCode(),result.getMsg());
        }

        LinkedHashMap map = (LinkedHashMap) result.getData();
        if(EmptyUtil.isEmpty(result.getData())){
            return null;
        }

        ObjectMapper mapper = new ObjectMapper();

        T res = mapper.convertValue(map, clazz);
        return res;
    }

    /**
     * @author: xurs
     * @date: 19-3-11
     * @Description:  list(List<LinkedHashMap>)转原list
     */
    public static <T> List<T> list2Object(Result result, Class<T> clazz){
        if(result.getCode().equals(ResultEnum.ERROR.getCode())){
            throw new MyException(ResultEnum.ERROR.getCode(),result.getMsg());
        }

        List<LinkedHashMap> mapList = (List<LinkedHashMap>) result.getData();
        if(EmptyUtil.isEmpty(result.getData())){
            return null;
        }

        ObjectMapper mapper = new ObjectMapper();
        List<T> list = new ArrayList<>();

        for (LinkedHashMap map: mapList) {
            T res = mapper.convertValue(map, clazz);
            list.add(res);
        }

        return list;
    }
}
